﻿using AutoMapper;
using Domain.Factory_Modeling;
using Infratructure.Interface;
using MediatR;
using ReturnValue;
using Yitter.IdGenerator;

namespace MES.Server.API.Application.Command.Factory_Modeling
{
    public class AddProductionLineHander : IRequestHandler<AddProductionLineCommand, ApiResult<int>>
    {
        private readonly IRepository<ProductionLineModel> productionLineRepo;
        private readonly IMapper mapper;
        public AddProductionLineHander(IRepository<ProductionLineModel> productionLineRepo, IMapper mapper)
        {
            this.productionLineRepo = productionLineRepo;
            this.mapper = mapper;
        }
        /// <summary>
        /// 添加产线管理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(AddProductionLineCommand request, CancellationToken cancellationToken)
        {
            lock (this) { 
                
            }     
            var result = new ApiResult<int>();
            //产线管理编码不能重复
            var exists = productionLineRepo.GetAll().Where(a => a.ProductionLineCode == request.ProductionLineCode).FirstOrDefault();
            if (exists != null)
            {
                result.Code = StatusCode.Fail;
                result.Message = "该产线管理编码已存在，请重新输入！";
                return await  Task.FromResult(result);
            }
            var model = mapper.Map<ProductionLineModel>(request);
            model.Id = YitIdHelper.NextId();
            model.CreateTime = DateTime.Now;
            model.IsDel = false;
            if (model != null)
            {
                await productionLineRepo.AddAsync(model);
                result.Code = StatusCode.Success;
                result.Message = "添加成功！";
                return await  Task.FromResult(result);
            }
            else
            {
                result.Code = StatusCode.Fail;
                result.Message = "添加失败！";
                return await Task.FromResult(result);
            }
        }
    }
}
